// lib/pages/search_result_page.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_shop/models/product.dart';
import 'package:multi_shop/services/product_api.dart';
import 'package:multi_shop/widgets/goods.dart';

class SearchResultPage extends StatefulWidget {
  const SearchResultPage({super.key});

  @override
  State<SearchResultPage> createState() => _SearchResultPageState();
}

class _SearchResultPageState extends State<SearchResultPage> {
  late String q;
  Future<List<Product>>? _futureList;

  final _api = ProductApi();

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    q = args["q"];
    getProducts(keyworld: q);
  }

  // 加载商品列表
  Future<void> getProducts({String? keyworld}) async {
    final data = await _api.list(keyword: keyworld);
    setState(() {
      _futureList = Future.value(data);
    });
  }

  void _doSearch(String newQ) {
    setState(() {
      q = newQ;
      getProducts(); // 真实项目：换成你的 API
    });
  }

  @override
  Widget build(BuildContext context) {
    final inputCtrl = TextEditingController(text: q);

    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        title: Container(
          margin: const EdgeInsets.only(right: 8),
          padding: const EdgeInsets.symmetric(horizontal: 8),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            children: [
              const SizedBox(width: 6),
              Expanded(
                child: TextField(
                  enabled: true,
                  controller: inputCtrl,
                  autofocus: true,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (_) => _doSearch(inputCtrl.text),
                  decoration: InputDecoration(
                    hintText: '搜索商品',
                    isCollapsed: true,
                    contentPadding: const EdgeInsets.symmetric(
                      vertical: 12,
                      horizontal: 12,
                    ),
                    prefixIcon: const Icon(Icons.search),
                    border: InputBorder.none,
                    filled: true,
                    fillColor: Colors.grey.withValues(
                      alpha: 0.1,
                    ), // 避免 withOpacity 警告
                  ),
                ),
              ),
              TextButton(
                onPressed: () => _doSearch(inputCtrl.text),
                child: const Text('搜索'),
              ),
            ],
          ),
        ),
      ),
      body: FutureBuilder<List<Product>>(
        future: _futureList,
        builder: (context, snap) {
          if (snap.connectionState != ConnectionState.done) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snap.hasError) {
            return Center(child: Text('加载失败：${snap.error}'));
          }
          final list = snap.data ?? [];
          if (list.isEmpty) {
            return const Center(child: Text('没有找到相关商品'));
          }
          return GridView.builder(
            padding: const EdgeInsets.all(12),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
              childAspectRatio: 0.7,
            ),
            itemCount: list.length,
            itemBuilder: (_, i) {
              final item = list[i];
              final defaultSku = item.skus.firstWhere(
                (sku) => sku.id.toString() == item.defaultSkuId.toString(),
              );
              final price = defaultSku.price.toString();

              return InkWell(
                onTap: () => Get.toNamed('/detail', arguments: item.id),
                child: ProductCard(
                  imageUrl: item.imageUrl.split(",")[0],
                  name: item.name,
                  price: price,
                  sales: item.sales,
                ),
              );
            },
          );
        },
      ),
    );
  }
}
